package app.base.systemmanage.systemrolespermsmanage;

import java.io.IOException;
import java.io.PrintWriter;
import java.net.URLDecoder;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.dao.DataIntegrityViolationException;

import app.base.common.Utility;

import app.base.systemmanage.systemrolespermsmanage.dao.SysRolesPermsMappingDAO;
import app.base.systemmanage.systemrolespermsmanage.model.SysRolesPermsMapping;
import app.base.systemmanage.systemrolespermsmanage.model.SysRolesPermsMappingExample;
import app.base.systemmanage.systemrolespermsmanage.model.SysRolesPermsMappingExample.Criteria;

public class SystemRolesPermsHandle extends HttpServlet{

	private static final long serialVersionUID = 1L;
		
	public void doGet(HttpServletRequest request, HttpServletResponse response) 
		throws ServletException, IOException 
	{
	    request.setCharacterEncoding(Utility.CHARSET_ENCODING_UTF8);
	    response.setContentType(Utility.DEFAULT_CONTENT_TYPE);

		PrintWriter out = response.getWriter(); 
						
		String cmd = request.getParameter("SYS_OP_CMD");
		
		String result = null;

		if (cmd == null || cmd.trim().length() == 0)
		{
			result = "{returnCode: '-1', msg: '客户端的数据请求命令参数CMD为设置错误'}";
		}
		else
		{
			cmd = cmd.trim();
			
			if (cmd.equals(Utility.SYS_OPERATION_COMMAND_ADD))
			{	
			    Map<String, Object>  map = new HashMap<String, Object>();
			    
				map.put("roleIds", URLDecoder.decode(request.getParameter("ROLE_ID").trim(), Utility.CHARSET_ENCODING_UTF8));
				map.put("permIds", URLDecoder.decode(request.getParameter("PERM_ID").trim(), Utility.CHARSET_ENCODING_UTF8));
				
				result = doSystemOperations(cmd, map);
			}
			else if (cmd.equals(Utility.SYS_OPERATION_COMMAND_DELETE))
			{
				result = doSystemOperations(cmd, URLDecoder.decode(request.getParameter("ROLE_PERM_ID").trim(), Utility.CHARSET_ENCODING_UTF8));
			}
			else
			{
				result = "{returnCode: '-1', msg: '服务器不支持的数据请求命令，请检查后再重试'}";
			}			
			
		}
		
		out.println(result);
		
		out.flush();
		out.close();
	}
	
	public void doPost(HttpServletRequest request, HttpServletResponse response) 
		throws ServletException, IOException 
	{
		doGet(request, response);
	}
	
	@SuppressWarnings("unchecked")
	private String doSystemOperations(String action, Object o)
	{
		
		String result = "{returnCode: '-1', msg: '系统调用函数 doSystemOperations() 失败'}";
		
		ApplicationContext context = new ClassPathXmlApplicationContext(Utility.DEFAULT_SPRINGFRAMEWORK_APPLICATION_CONTEXT_FILE_PATH);
		SysRolesPermsMappingDAO sysRolesPermsMappingDAO = (SysRolesPermsMappingDAO)context.getBean(Utility.SYSTEM_ROLES_PERMS_MAPPING_MANAGE_MODULE_BEAN_NAME);
		
		if (action.equals(Utility.SYS_OPERATION_COMMAND_ADD))
		{
			result = insert(sysRolesPermsMappingDAO, (Map<String, Object>) o);
		}
		else if (action.equals(Utility.SYS_OPERATION_COMMAND_DELETE))
		{			
			result = delete(sysRolesPermsMappingDAO, (String) o);
		}
		
		return result;
	}
	
	private String insert(SysRolesPermsMappingDAO sysRolesPermsMappingDAO, Map<String, Object> map)
	{
		String result = "{returnCode: '0', msg: '分配角色权限成功'}";
		
		SysRolesPermsMapping record = new SysRolesPermsMapping();

		try {
			String [] roleIds = map.get("roleIds").toString().split("\\" + Utility.SPLIT_CHARS_VERTICAL_LINE);
			String [] permIds = map.get("permIds").toString().split("\\" + Utility.SPLIT_CHARS_VERTICAL_LINE);
			
			sysRolesPermsMappingDAO.getMySqlMapClient().startTransaction();
			
			for (int i = 0; i < roleIds.length; i++)
			{
				record.setROLE_ID(roleIds[i]);
				for (int j = 0; j < permIds.length; j++)
				{
					record.setPERM_ID(permIds[j]);
					try {
						sysRolesPermsMappingDAO.insert_0001(record);		
					}
					catch(DataIntegrityViolationException e) {
					}
				}				
			}

			sysRolesPermsMappingDAO.getMySqlMapClient().commitTransaction();
		} 
		catch (Exception e) {
			e.printStackTrace();
			result = "{returnCode: '-1', msg: " + e.toString() + "'}";
		}
		finally{
			try {
				sysRolesPermsMappingDAO.getMySqlMapClient().endTransaction();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		
		return result;
	}
	
	private String delete(SysRolesPermsMappingDAO sysRolesPermsMappingDAO, String rolePermId)
	{
		String result = "{returnCode: '0', msg: '删除角色权限成功'}";
		
		try {
			String [] rolePermIds = rolePermId.split("\\" + Utility.SPLIT_CHARS_VERTICAL_LINE);
			
			List<String> roPermIds = new ArrayList<String>();
			
			for (int index = 0; index < rolePermIds.length; index++) 
			{
				roPermIds.add(rolePermIds[index]);
			}

			SysRolesPermsMappingExample example = new SysRolesPermsMappingExample();
			
			Criteria criteria = example.createCriteria();
			
			criteria.andROLE_PERM_IDIn(roPermIds);
			
			sysRolesPermsMappingDAO.deleteByExample(example);	
		} 
		catch (Exception e) 
		{
			e.printStackTrace();
			result = "{returnCode: '-1', msg: " + e.toString() + "'}";
		}
		
		return result;
	}	
	
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		/*String [] permIds = "SYSMENUIDROOTNODESYSMAINFRM".split("\\" + Utility.SPLIT_CHARS_VERTICAL_LINE);
		

		for (int count = 0; count < permIds.length; count++)
		{
			System.out.println(permIds[count]);
		}*/
	}

}